﻿using System;
using biz.ritter.javapi.xml;
using biz.ritter.javapi.util;


namespace Nofs.Net.nofs.metadata.XMLDriver
{

    public sealed class XMLHelper
    {
        //@SuppressWarnings("unchecked")
        public static Branch TryToFindChildByName(Branch node, String name)
        {
            for (Iterator<Branch> iter = node.nodeIterator(); iter.hasNext(); )
            {
                Object obj = iter.next();
                if (obj is Branch)
                {
                    Branch child = (Branch)obj;
                    if (child.getName().compareTo(name) == 0)
                    {
                        return child;
                    }
                }
            }
            return null;
        }

        //@SuppressWarnings("unchecked")
        public static LinkedList<Branch> FindChildrenByName(Branch node, String name)
        {
            LinkedList<Branch> children = new LinkedList<Branch>();
            for (Iterator<Branch> iter = node.nodeIterator(); iter.hasNext(); )
            {
                Object obj = iter.next();
                if (obj is Branch)
                {
                    Branch child = (Branch)obj;
                    if (child.getName().compareTo(name) == 0)
                    {
                        children.add(child);
                    }
                }
            }
            return children;
        }

        public static String TryReadContents(Branch node, String defaultValue)
        {
            if (node != null)
            {
                return node.getText();
            }
            return defaultValue;
        }

        public static String TryReadChildContents(Branch node, String childName, String defaultValue)
        {
            return XMLHelper.TryReadContents(XMLHelper.TryToFindChildByName(node, childName), null);
        }

        //@SuppressWarnings("unchecked")
        public static LinkedList<Branch> GetChildren(Branch node)
        {
            LinkedList<Branch> children = new LinkedList<Branch>();
            for (Iterator<Branch> iter = node.nodeIterator(); iter.hasNext(); )
            {
                Object obj = iter.next();
                if (obj is Branch)
                {
                    Branch child = (Branch)obj;
                    children.add(child);
                }
            }
            return children;
        }
    }
}
